﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using umbraco.interfaces;
using umbraco.cms.businesslogic.datatype;
using System.Web.UI;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
using System.Collections;
using System.Drawing;

namespace MT.Flag.Umbraco.DataTypes.TabularData
{
    class TabularDataPrevalueEditor : PlaceHolder, IDataPrevalue
    {

        // referenced datatype
        private BaseDataType _datatype;

        private TextBox _txtRows;
        private TextBox _txtCols;
        private CheckBox _chkHeaderCol;
        private CheckBox _chkHeaderRow;
        private CheckBox _chkFooterRow;
        private TextBox _txtHeaderColWidth;
        private TextBox _txtDefaultColWidth;

        private RequiredFieldValidator _rfvRows;
        private RegularExpressionValidator _rxRows;

        private RequiredFieldValidator _rfvCols;
        private RegularExpressionValidator _rxCols;

        private RequiredFieldValidator _rfvHeaderColWidth;
        private RegularExpressionValidator _rxHeaderColWidth;

        private RequiredFieldValidator _rfvDefaultColWidth;
        private RegularExpressionValidator _rxDefaultColWidth;


        public TabularDataPrevalueEditor(BaseDataType DataType)
        {
            _datatype = DataType;
            setupChildControls();
        }


        private void setupChildControls()
        {
            _txtRows = new TextBox();
            _txtRows.ID = "txtRows";
            Controls.Add(_txtRows);

            _rfvRows = new RequiredFieldValidator();
            _rfvRows.ControlToValidate = _txtRows.ID;
            _rfvRows.Display = ValidatorDisplay.Dynamic;
            _rfvRows.Text = "*";
            _rfvRows.ToolTip = "You must enter the default number of rows.";
            _rfvRows.ForeColor = Color.FromName("Red"); ;
            Controls.Add(_rfvRows);

            _rxRows = new RegularExpressionValidator();
            _rxRows.ControlToValidate = _txtRows.ID;
            _rxRows.Display = ValidatorDisplay.Dynamic;
            _rxRows.Text = "*";
            _rxRows.ToolTip = "Rows must be a positive whole number.";
            _rxRows.ForeColor = Color.FromName("Red"); ;
            _rxRows.ValidationExpression = "^[1-9]([0-9]+)?";
            Controls.Add(_rxRows);

            
            _txtCols = new TextBox();
            _txtCols.ID = "txtCols";
            Controls.Add(_txtCols);

            _rfvCols = new RequiredFieldValidator();
            _rfvCols.ControlToValidate = _txtCols.ID;
            _rfvCols.Display = ValidatorDisplay.Dynamic;
            _rfvCols.Text = "*";
            _rfvCols.ToolTip = "You must enter the default number of columns.";
            _rfvCols.ForeColor = Color.FromName("Red");
            Controls.Add(_rfvCols);

            _rxCols = new RegularExpressionValidator();
            _rxCols.ControlToValidate = _txtCols.ID;
            _rxCols.Display = ValidatorDisplay.Dynamic;
            _rxCols.Text = "*";
            _rxCols.ToolTip = "Columns must be a positive whole number.";
            _rxCols.ForeColor = Color.FromName("Red"); ;
            _rxCols.ValidationExpression = "^[1-9]([0-9]+)?";
            Controls.Add(_rxCols);

            

            _chkHeaderCol = new CheckBox();
            _chkHeaderCol.ID = "chkHeaderCol";
            Controls.Add(_chkHeaderCol);

            _chkHeaderRow = new CheckBox();
            _chkHeaderRow.ID = "chkHeaderRow";
            Controls.Add(_chkHeaderRow);

            _chkFooterRow = new CheckBox();
            _chkFooterRow.ID = "chkFooterRow";
            Controls.Add(_chkFooterRow);



            _txtHeaderColWidth = new TextBox();
            _txtHeaderColWidth.ID = "txtHeaderColWidth";
            _txtHeaderColWidth.Text = "140"; // default value
            Controls.Add(_txtHeaderColWidth);

            _rfvHeaderColWidth = new RequiredFieldValidator();
            _rfvHeaderColWidth.ControlToValidate = _txtHeaderColWidth.ID;
            _rfvHeaderColWidth.Display = ValidatorDisplay.Dynamic;
            _rfvHeaderColWidth.Text = "*";
            _rfvHeaderColWidth.ToolTip = "You must enter the initial header column width.";
            _rfvHeaderColWidth.ForeColor = Color.FromName("Red"); ;
            Controls.Add(_rfvHeaderColWidth);

            _rxHeaderColWidth = new RegularExpressionValidator();
            _rxHeaderColWidth.ControlToValidate = _txtHeaderColWidth.ID;
            _rxHeaderColWidth.Display = ValidatorDisplay.Dynamic;
            _rxHeaderColWidth.Text = "*";
            _rxHeaderColWidth.ToolTip = "Initial header column width must be a positive whole number.";
            _rxHeaderColWidth.ForeColor = Color.FromName("Red"); ;
            _rxHeaderColWidth.ValidationExpression = "^[1-9]([0-9]+)?";
            Controls.Add(_rxHeaderColWidth);


            _txtDefaultColWidth = new TextBox();
            _txtDefaultColWidth.ID = "txtDefaultColWidth";
            _txtDefaultColWidth.Text = "90"; // default value
            Controls.Add(_txtDefaultColWidth);

            _rfvDefaultColWidth = new RequiredFieldValidator();
            _rfvDefaultColWidth.ControlToValidate = _txtDefaultColWidth.ID;
            _rfvDefaultColWidth.Display = ValidatorDisplay.Dynamic;
            _rfvDefaultColWidth.Text = "*";
            _rfvDefaultColWidth.ToolTip = "You must enter the initial default column width.";
            _rfvDefaultColWidth.ForeColor = Color.FromName("Red"); ;
            Controls.Add(_rfvDefaultColWidth);

            _rxDefaultColWidth = new RegularExpressionValidator();
            _rxDefaultColWidth.ControlToValidate = _txtDefaultColWidth.ID;
            _rxDefaultColWidth.Display = ValidatorDisplay.Dynamic;
            _rxDefaultColWidth.Text = "*";
            _rxDefaultColWidth.ToolTip = "Initial default column width must be a positive whole number.";
            _rxDefaultColWidth.ForeColor = Color.FromName("Red"); ;
            _rxDefaultColWidth.ValidationExpression = "^[1-9]([0-9]+)?";
            Controls.Add(_rxDefaultColWidth);


            // umbraco.uicontrols.PropertyPanel ppRows = new umbraco.uicontrols.PropertyPanel();
            // Controls.Add(ppRows); ??

        }



        public Control Editor
        {
            get { return this; }
        }


        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!Page.IsPostBack)
            {
                SortedList s = StoredConfiguration;

                if (s.ContainsKey("rows"))
                    _txtRows.Text = s.GetByIndex(s.IndexOfKey("rows")).ToString();

                if (s.ContainsKey("cols"))
                    _txtCols.Text = s.GetByIndex(s.IndexOfKey("cols")).ToString();

                if (s.ContainsKey("headercol"))
                    _chkHeaderCol.Checked = s.GetByIndex(s.IndexOfKey("headercol")).ToString() == "1";

                if (s.ContainsKey("headerrow"))
                    _chkHeaderRow.Checked = s.GetByIndex(s.IndexOfKey("headerrow")).ToString() == "1";

                if (s.ContainsKey("footerrow"))
                    _chkFooterRow.Checked = s.GetByIndex(s.IndexOfKey("footerrow")).ToString() == "1";

                if (s.ContainsKey("headerwidth"))
                    _txtHeaderColWidth.Text = s.GetByIndex(s.IndexOfKey("headerwidth")).ToString();

                if (s.ContainsKey("defaultwidth"))
                    _txtDefaultColWidth.Text = s.GetByIndex(s.IndexOfKey("defaultwidth")).ToString();
 
            }
        }

        public void Save()
        {
            if(_datatype.DBType != DBTypes.Ntext)
                _datatype.DBType = (DBTypes)Enum.Parse(typeof(DBTypes), DBTypes.Ntext.ToString(), true);

            // delete the existing values
            SqlHelper.ExecuteNonQuery("delete from cmsDataTypePreValues where datatypenodeid = @dtdefid", SqlHelper.CreateParameter("@dtdefid", _datatype.DataTypeDefinitionId)); 

            // insert the current values
            SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'rows')", SqlHelper.CreateParameter("@dtdefid", _datatype.DataTypeDefinitionId), SqlHelper.CreateParameter("@value", _txtRows.Text));
            SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'cols')", SqlHelper.CreateParameter("@dtdefid", _datatype.DataTypeDefinitionId), SqlHelper.CreateParameter("@value", _txtCols.Text));
            SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'headercol')", SqlHelper.CreateParameter("@dtdefid", _datatype.DataTypeDefinitionId), SqlHelper.CreateParameter("@value", _chkHeaderCol.Checked ? "1" : "0"));
            SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'headerrow')", SqlHelper.CreateParameter("@dtdefid", _datatype.DataTypeDefinitionId), SqlHelper.CreateParameter("@value", _chkHeaderRow.Checked ? "1" : "0"));
            SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'footerrow')", SqlHelper.CreateParameter("@dtdefid", _datatype.DataTypeDefinitionId), SqlHelper.CreateParameter("@value", _chkFooterRow.Checked ? "1" : "0"));
            SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'headerwidth')", SqlHelper.CreateParameter("@dtdefid", _datatype.DataTypeDefinitionId), SqlHelper.CreateParameter("@value", _txtHeaderColWidth.Text));
            SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'defaultwidth')", SqlHelper.CreateParameter("@dtdefid", _datatype.DataTypeDefinitionId), SqlHelper.CreateParameter("@value", _txtDefaultColWidth.Text));
        }


        



        protected override void Render(HtmlTextWriter writer)
        {
            //writer.Write("<div class=\"propertypane\">");

            writer.Write("<div class=\"propertyItem\"><div class=\"propertyItemheader\">Rows<br /><small>Default number of rows (must be at least 1)</small></div><div class=\"propertyItemContent\">");
            _txtRows.RenderControl(writer);
            _rfvRows.RenderControl(writer);
            _rxRows.RenderControl(writer);
            writer.Write("</div></div>");

            writer.Write("<div class=\"propertyItem\"><div class=\"propertyItemheader\">Columns<br /><small>Default number of columns (must be at least 1)</small></div><div class=\"propertyItemContent\">");
            _txtCols.RenderControl(writer);
            _rfvCols.RenderControl(writer);
            _rxCols.RenderControl(writer);
            writer.Write("</div></div>");

            writer.Write("<div class=\"propertyItem\"><div class=\"propertyItemheader\">Header column<br /><small>Include a header column</small></div><div class=\"propertyItemContent\">");
            _chkHeaderCol.RenderControl(writer);
            writer.Write("</div></div>");

            writer.Write("<div class=\"propertyItem\"><div class=\"propertyItemheader\">Header row<br /><small>Include a header row</small></div><div class=\"propertyItemContent\">");
            _chkHeaderRow.RenderControl(writer);
            writer.Write("</div></div>");

            writer.Write("<div class=\"propertyItem\"><div class=\"propertyItemheader\">Footer row<br /><small>Include a footer row</small></div><div class=\"propertyItemContent\">");
            _chkFooterRow.RenderControl(writer);
            writer.Write("</div></div>");


            writer.Write("<div class=\"propertyItem\"><div class=\"propertyItemheader\">Initial header column width<br /><small>(pixels)</small></div><div class=\"propertyItemContent\">");
            _txtHeaderColWidth.RenderControl(writer);
            writer.Write("</div></div>");

            writer.Write("<div class=\"propertyItem\"><div class=\"propertyItemheader\">Initial column width<br /><small>(pixels)</small></div><div class=\"propertyItemContent\">");
            _txtDefaultColWidth.RenderControl(writer);
            writer.Write("</div></div>");

            //writer.Write("</div>");
        
        }



        public SortedList StoredConfiguration
        {
            get
            {
                // read values from the database
                IRecordsReader rr = SqlHelper.ExecuteReader("select alias, value from cmsDataTypePreValues where datatypenodeid = @datatypenodeid", SqlHelper.CreateParameter("@datatypenodeid", _datatype.DataTypeDefinitionId));

                // array for stored configuration values
                SortedList values = new SortedList();

                // go through the values from the database and store them in the array
                while (rr.Read())
                {
                    if(!values.ContainsKey(rr.GetString("alias")))
                        values.Add(rr.GetString("alias"), rr.GetString("value"));
                }

                return values;
            }
        }



        /// <summary>
        /// Gets the Umbraco SQL helper.
        /// </summary>
        /// <value>The SQL helper.</value>
        public static ISqlHelper SqlHelper
        {
            get
            {
                return Application.SqlHelper;
            }
        }

    }
}
